<template>
  <div class="articleList">
    <van-pull-refresh v-model="VanIsLoading" @refresh="onRefresh" :success-duration="1500" :success-text="tipText">
      <van-list v-model="loading" :finished="finished" finished-text="小子，到底了" @load="onLoad" :error.sync="error"
        error-text="请求失败，点击重新加载">
        <Article :article="item" v-for="item in list" :key="item.art_id+ ''" />
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getArticle } from '../../../api/article'
import Article from '../../../components/article/index.vue'
export default {
  components: {
    Article
  },
  data () {
    return {
      list: [],
      // 底部下拉状态
      loading: false,
      // 是否完成
      finished: false,
      // 时间戳
      pre_timestamp: Date.now(),
      error: false,
      // 是否处于加载中
      VanIsLoading: false,
      // 下拉刷新提示文本
      tipText: ''
    }
  },
  props: {
    // 频道id
    pannelId: {
      require: true,
      type: Number
    }
  },
  methods: {
    // 触发事件函数
    // 1组件创建的时候，2数据没有占满一整屏的时候，3触底的时候
    async onLoad () {
      try {
        // 1发送请求
        const { data: res } = await getArticle({
          channel_id: this.pannelId,
          timestamp: this.pre_timestamp,
          with_top: 0
        })
        // 随机出错
        // if (Math.random() > 0.5) {
        //   console.lg(123)
        // }
        console.log(res)
        // 2，将数据保存到list
        this.list.push(...res.data.results)
        // 3保存时间搓
        this.pre_timestamp = res.data.pre_timestamp
        // 4加载状态结束
        this.loading = false
        // 5判断下页还有没有数据
        if (!res.data.results.length) {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
      // 数据全部加载完成
    },
    // 下拉刷新触发
    async onRefresh () {
      try {
        const { data: res } = await getArticle({
          channel_id: this.pannelId,
          timestamp: Date.now(),
          with_top: 0
        })
        console.log(res)
        this.list.unshift(...res.data.results)
        this.VanIsLoading = false
        this.tipText = '小子共加载' + res.data.results.length + '条'
      } catch (err) {
        // 关闭下拉loading
        this.VanIsLoading = false
        this.tipText = '加载失败，请重试'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.articleList {
  height: 80vh;
  overflow-y: scroll;
}
</style>>
